package com.itheima.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Map;

/**
 * 自定义导出数据的引擎
 *
 * @author mewp
 * @date 2022/12/03 14:42
 **/
public class ExcelExportEngine {

    public static Workbook writeToExcel(Object object, Workbook workbook, String photoPath) throws Exception {
        //将实体bean转换成map
        Map<String, Object> map = EntityUtils.entityToMap(object);
        //循环遍历每一对数据，把日期型的转换成字符串，方便导出
/*        for (String key : map.keySet()) {
            Object value = map.get(key);
            if (value instanceof Date) {
                System.out.println(sdf.format(value));
                map.put(key, sdf.format(value));
            }
        }*/

        //获取第一个sheet，整体的思路是循环100个行的100个单元
        Sheet sheet = workbook.getSheetAt(0);
        Cell cell = null;
        Row row = null;
        for (int i = 0; i < 100; i++) {
            row = sheet.getRow(i);
            //获取到空行为止
            if (row == null) {
                break;
            } else {
                for (int j = 0; j < 100; j++) {
                    //获取到空单元格不处理
                    cell = row.getCell(j);
                    if (cell != null) {
                        //开始向单元格中写内容
                        writeCell(cell, map);
                    }
                }
            }
        }

        //处理照片
        if (StringUtils.isNotBlank(photoPath)) {
            File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            BufferedImage bufferedImage = ImageIO.read(new File(photoPath));
            String extName = photoPath.substring(photoPath.lastIndexOf(".") + 1).toUpperCase();
            ImageIO.write(bufferedImage, extName, byteArrayOut);
            //创建一个绘图控制类，负责画图
            Drawing patriarch = sheet.createDrawingPatriarch();
            //指定把图片放到哪个位置
            Sheet sheet1 = workbook.getSheetAt(1);
            //开始列 开始行 结束列 结束行 偏移的单位：是一个英式公制的单位 1cm=360000
            int col1 = ((Double) sheet1.getRow(0).getCell(0).getNumericCellValue()).intValue();
            int row1 = ((Double) sheet1.getRow(0).getCell(1).getNumericCellValue()).intValue();
            int col2 = ((Double) sheet1.getRow(0).getCell(2).getNumericCellValue()).intValue();
            int row2 = ((Double) sheet1.getRow(0).getCell(3).getNumericCellValue()).intValue();
            ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col1, row1, col2, row2);
            int format = 0;
            switch (extName) {
                case "JPG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                    break;
                case "JPEG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                    break;
                case "PNG":
                    format = XSSFWorkbook.PICTURE_TYPE_PNG;
            }
            //把图片写入到sheet指定的位置
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), format));
            workbook.removeSheetAt(1);
        }
        return workbook;
    }

    /**
     * 比较单元格中的值，是否和map中的key一致，如果一致向单元格中放入map这个key对应的值
     *
     * @param cell
     * @param map
     */
    private static void writeCell(Cell cell, Map<String, Object> map) {
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case FORMULA:
                break;
            default: {
                String cellValue = cell.getStringCellValue();
                if (StringUtils.isNotBlank(cellValue)) {
                    for (String key : map.keySet()) {
                        if (key.equals(cellValue)) {
                            cell.setCellValue(map.get(key).toString());
                        }
                    }
                }
            }
        }
    }
}
